import { message } from 'antd';
import pathToRegExp from 'path-to-regexp';
import { normalize, schema } from 'normalizr';
let configA = {
  authDomain: "kmxxg-chat.wilddog.com",
  syncURL: "https://kmxxg-chat.wilddogio.com"
};

wilddog.initializeApp(configA);
let chatAppRef;
let upRef;
let roomMetaRef;
let roomMessageRef;
let usersRef;

function setWilddog() {
  chatAppRef = wilddog.sync();
  upRef = wilddog.sync().ref("up-metadata");
  roomMetaRef = wilddog.sync().ref("room-metadata");
  roomMessageRef = wilddog.sync().ref("room-messages");
  usersRef = wilddog.sync().ref("users");
}
let provider = new wilddog.auth.WeixinAuthProvider();



const upSchema = new schema.Entity('ups');
const upListSchema = [upSchema];
export default {
  namespace: 'wilddog',
  state: {
    auth: {
      status: false
    }
  },
  subscriptions: {
    setup: function({ history, dispatch }) {
      history.listen(({ pathname }) => {
        // console.log(pathToRegExp('/wilddog/:type/:roomId').exec(pathname),pathname)
        let wilddogPath = pathToRegExp('/wilddog/:type').exec(pathname);

        let messagePath = pathToRegExp('/wilddog/room/:roomId').exec(pathname);

        if (wilddogPath || messagePath) {
          setWilddog();
          wilddog.auth().onAuthStateChanged(function(user) {
            if (user != null) {
              // console.log(user);
              setWilddog();
              dispatch({ type: 'loginSuccess', payload: user })
            } else {
              console.log('未检测到用户')
            }
          });
        }
        if (messagePath) {
          dispatch({ type: 'getMessages', payload: messagePath[1] });
        }
        if (wilddogPath) {
          if (wilddogPath[1] == 'wilddogRoom') {
            dispatch({ type: 'getRooms' })
          } else {
            dispatch({ type: 'getUpList' });
          }
        }
      });
    }
  },
  effects: { * login({}, { call, put }) {
      try {
        wilddog.auth().signInWithPopup(provider);
      } catch (err) {
        console.log(err)
      }
    },
    * getUpList({ payload }, { call, put }) {
      try {
        const data = yield upRef.orderByChild('createdAt').limitToLast(1000).once('value');
        // console.log(data.val());
        if (data.val()) {
          yield put({ type: 'getUpListSuccess', payload: data.val() });
        } else {
          message.error('获取数据失败', 5);
        }
      } catch (err) {
        message.error(err, 5);
      }
    },
    * addOneUp({ payload }, { call, put }) {
      try {
        let newUpRef = upRef.push();
        payload = Object.assign({}, payload, { createdAt: upRef.ServerValue.TIMESTAMP, id: newUpRef.key() });
        yield newUpRef.set(payload);
        yield put({ type: 'getUpList' })
      } catch (err) {
        message.error('添加点赞活动失败', 5);
      }

    },
    * deleteOneUp({ payload }, { call, put }) {
      try {
        yield upRef.ref(payload).set(null);
        yield put({ type: 'getUpList' })
      } catch (err) {
        message.error('删除点赞活动失败', 5);
      }
    },
    * updateUpCount({ payload }, { call, put }) {
      try {
        const { id } = payload;
        yield upRef.child(id).set(payload);
        yield put({ type: 'getUpList' })
      } catch (err) {
        message.error('修改失败', 5);
      }
    },
    * getRooms({ payload }, { call, put }) {
      try {
        const data = yield roomMetaRef.orderByChild('createdAt').limitToLast(1000).once('value');
        yield put({ type: 'getRoomsSuccess', payload: data.val() });
      } catch (err) {
        message.error('获取聊天室列表失败', 5);
      }
    },
    * addOneRoom({ payload }, { call, put }) {
      try {
        let newRoomRef = roomMetaRef.push();
        payload = Object.assign({}, payload, { createdAt: roomMetaRef.ServerValue.TIMESTAMP, id: newRoomRef.key() });
        yield roomMetaRef.child(newRoomRef.key()).set(payload);
        yield put({ type: 'getRooms' });
      } catch (err) {
        message.error('创建留言失败', 5);
      }
    },
    * getMessages({ payload }, { call, put }) {
      try {
        // console.log(payload)
        const data = yield roomMessageRef.ref(payload).orderByChild('timestamp').limitToLast(2000).once('value');
        // console.log(data.val(),payload);
        yield put({ type: 'getMessagesSuccess', payload: data.val() });
      } catch (err) {
        message.error('获取留言列表失败', 5);
      }
    },
    * getMoreMessages({ payload }, { call, put }) {
      try {
        let { roomId, messageId } = payload;
        yield roomMessageRef.ref(roomId).orderByChild('timestamp').limitToFirst(2000).once('value');
        yield put({ type: 'getMoreMessagesSuccess' });
      } catch (err) {
        message.error('获取更多留言列表失败', 5);
      }
    },
    * delOneMessage({ payload }, { call, put }) {
      try {
        yield wilddog.sync().ref(`room-messages/${payload.roomId}/${payload.id}`).set(null);
        yield put({ type: 'delOneMessageSuccess', payload: payload });
      } catch (err) {
        message.error('删除留言失败', 5);
      }
    },
    * delMessages({ payload }, { call, put }) {
      try {
        let delQueue = [];
        let { messageInfo } = payload;
        messageInfo.map(id => {
          delQueue.push(wilddog.sync().ref(`room-messages/${payload.roomId}/${id}`).set(null));
          return id
        });
        yield [delQueue];
        yield put({ type: 'delMessagesSuccess', payload: payload });
      } catch (err) {
        message.error('批量删除留言失败', 5);
      }
    },
    * updateMessage({ payload }, { call, put }) {
      try {
        // console.log(payload)
        yield wilddog.sync().ref(`room-messages/${payload.roomId}/${payload.message.id}`).set(payload.message)
        yield put({ type: 'updateMessageSuccess', payload: payload.message });
      } catch (err) {
        message.error('审核留言失败', 5);
      }
    },
    * addMessage({ payload }, { call, put }) {
      try {
        let { roomId } = payload;
        let newRoomMessageRef = roomMessageRef.child(roomId).push();
        let message = Object.assign({}, payload.messageInfo, { timestamp: roomMessageRef.ServerValue.TIMESTAMP, id: newRoomMessageRef.key() });
        // console.log(message);
        yield wilddog.sync().ref(`room-messages/${roomId}/${newRoomMessageRef.key()}`).set(message);
        yield put({ type: 'getMessages', payload: roomId });
      } catch (err) {
        message.error('添加留言失败', 5);
      }
    },
    * getUser({ paylaod }, { take, put }) {
      try {
        yield wilddog.sync().ref('users').child(userId).once('value');
        yield put({ type: 'getUserSuccess' });
      } catch (err) {
        message.error('添加留言失败', 5);
      }
    }

  },
  reducers: {
    getUpListSuccess(state, { payload }) {

      let upList = Object.keys(payload).map(item => payload[item]).reverse();
      // const normalized = normalize(upList,upListSchema );
      // console.log(upList,normalized);
      return {
        ...state,
        upList

      }
    },
    loginSuccess(state, { payload }) {
      let { displayName, uid, photoURL, providerId } = payload;
      return Object.assign({}, state, { auth: { status: true, displayName: displayName, uid: uid, photoURL: photoURL, providerId: providerId } });
    },
    addRoomsSuccess(state, { payload }) {
      let roomList = Object.keys(payload).map(item => payload[item]).reverse();
      return {
        ...state,
        upList
      }
    },
    getRoomsSuccess(state, { payload }) {
      let roomList = Object.keys(payload).map(item => payload[item]).reverse();
      return {
        ...state,
        roomList
      }
    },
    getMessagesSuccess(state, { payload }) {
      // console.log(payload)
      let messageList = Object.keys(payload || {}).map(function(k) {
        payload[k].id = k;
        return payload[k];
      }).reverse();
      return {
        ...state,
        messageList
      }
    },
    getMoreMessagesSuccess(state, { payload }) {},
    delOneMessageSuccess(state, { payload }) {
      // console.log(payload,state)
      return Object.assign({}, state, {
        messageList: state.messageList.filter((item, index) => {
          console.log(item.id)
          return item.id != payload.id
        })
      });
    },
    delMessagesSuccess(state, { payload }) {

      let { messageInfo } = payload;
      return Object.assign({}, state, {
        messageList: state.messageList.filter((item, index) => {
          // console.log(item.id,messageInfo.some((choosed)=>{console.log(choosed,item.id); return choosed.id==item.id}))
          return (!messageInfo.some(choosed=>{return choosed==item.id}))
        })
     
      // return Object.assign({}, state, {
      //   messageList: state.messageList.filter((message,index) => {
      //     console.log(message.id)
      //     const flag= messageInfo.length>1
      //                   ?(!messageInfo.some(item=>{return item.id==message.id}))
      //                   :!(messageInfo[0].id==message.id)
      //       console.log(flag,messageInfo,message.id,messageInfo[0].id,message.id)
      //     return flag;
      //   })
    });
},
updateMessageSuccess(state, { payload }) {
    return Object.assign({}, state, {
      messageList: state.messageList.map((message) => {
        if (message.id === payload.id) {
          return Object.assign({}, message, { checked: payload.checked })
        }
        return message;
      })
    });
  },
  addMessageSuccess(state, { payload }) {},
  getUserSuccess(state, { payload }) {},

},
};
